<template>
  <a-card :bordered="false">
    <a-spin :spinning="isLoading">
      <!-- <div class="card-title">{{ $route.meta.title }}{{ data.pending.deliverOrderTotal }}</div> -->
      <div class="card-title" v-if="$route.meta.keys == 'all'">
        {{ $route.meta.title }}
        <span class="card-number">(待配送:{{ data.pending.deliverOrderTotal }})</span>
      </div>
      <div class="card-title" v-else>
        {{ $route.meta.title }}
        <span class="card-number">({{ orderList.total }})</span>
      </div>
      <div class="table-operator">
        <!-- 搜索板块 -->
        <a-row class="row-item-search">
          <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
            <a-form-item label="关键词">
              <a-input style="width: 337px" placeholder="请输入关键词" v-decorator="['searchValue']">
                <a-select slot="addonBefore" v-decorator="['searchType', { initialValue: 10 }]" style="width: 100px">
                  <a-select-option v-for="(item, index) in SearchTypeEnum" :key="index" :value="item.value">{{
                    item.name
                  }}</a-select-option>
                </a-select>
              </a-input>
            </a-form-item>
            <a-form-item label="门店">
              <a-select v-decorator="['orderSource', { initialValue: -1 }]">
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option v-for="item in shopListTreeData" :key="item.store_id" :value="item.store_id">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="支付方式">
              <a-select v-decorator="['payMethod', { initialValue: '' }]">
                <a-select-option value>全部</a-select-option>
                <a-select-option v-for="(item, key) in PaymentMethodEnum" :key="key" :value="key">{{
                  item
                }}</a-select-option>
              </a-select>
            </a-form-item>
            <!-- <a-form-item label="配送方式">
              <a-select v-decorator="['deliveryType', { initialValue: -1 }]">
                <a-select-option :value="-1">全部</a-select-option>
                <a-select-option v-for="(item, index) in DeliveryTypeEnum.data" :key="index" :value="item.value">{{
                  item.name
                }}</a-select-option>
              </a-select>
            </a-form-item> -->
            <a-form-item label="下单时间">
              <a-range-picker format="YYYY-MM-DD" v-decorator="['betweenTime']" />
            </a-form-item>
            <!-- <a-form-item label="选择地区">
              <SelectRegion placeholder="请选择省市区" v-decorator="['cascader']" />
            </a-form-item> -->
            <a-form-item class="search-btn">
              <a-button class="mr-15" type="primary" icon="search" html-type="submit">搜索</a-button>
              <!-- <a-button class="mr-15" type="primary" icon="plus" @click="addorder">录入订单</a-button> -->
              <a-button @click="handleReset">重置</a-button>
            </a-form-item>
          </a-form>
        </a-row>
      </div>
      <!-- 列表内容 -->
      <div class="ant-table ant-table-scroll-position-left ant-table-default ant-table-bordered">
        <div class="ant-table-content">
          <div class="ant-table-scroll">
            <div class="ant-table-body" style="overflow-x: scroll">
              <table style="width: 1450px">
                <thead class="ant-table-thead">
                  <tr>
                    <th v-for="(item, index) in columns" :key="index">
                      <span class="ant-table-header-column">
                        <div>
                          <span class="ant-table-column-title">{{ item.title }}</span>
                        </div>
                      </span>
                    </th>
                  </tr>
                </thead>
                <tbody class="ant-table-tbody">
                  <template v-for="item in orderList.data">
                    <tr class="order-empty" :key="`order_${item.order_id}_1`">
                      <td colspan="8"></td>
                    </tr>
                    <tr :key="`order_${item.order_id}_2`">
                      <td colspan="8">
                        <div class="orderinfo">
                          <span class="mr-20">{{ item.create_time }}</span>
                          <span class="mr-20">订单号：{{ item.order_id }}</span>
                          <span class="mr-20" style="color: lightcoral;">银豹订单号：{{ item.order_no }}</span>
                          <div class="shopinfo">
                            <img class="shopimg" src="~@/assets/logo.jpg" alt="">
                            <p class="ml-10" style="color: rgb(83, 133, 213) ;">{{ item.store_info.name }}</p>
                          </div>
                          <div style="color: brown;">
                            订单创建者：{{ item.create_order_username }}
                          </div>
                        </div>
                        <!-- <platform-icon :name="item.platform" :showTips="true" /> -->
                      </td>
                    </tr>
                    <tr v-for="(goodsItm, goodsIdx) in item.goods" :key="`orderGoods_${item.order_id}_${goodsIdx}`">
                      <td>
                        <GoodsItem :data="{
                          image: goodsItm.goods_image,
                          imageAlt: '商品图片',
                          title: goodsItm.goods_name,
                          goodsProps: goodsItm.goods_props,
                        }" />
                      </td>
                      <td>
                        <p>￥{{ goodsItm.total_pay_price }}</p>
                        <p>×{{ goodsItm.total_num }}</p>
                      </td>
                      <template v-if="goodsIdx === 0">
                        <td :rowspan="item.goods.length">
                          <p>￥{{ item.pay_price }}</p>
                          <p class="c-muted-1">(含运费：￥{{ item.express_price }})</p>
                        </td>
                        <td :rowspan="item.goods.length">
                          <!-- <UserItem :user="item.user" /> -->
                          <div class="userinfo">
                            <div class="userinfo_top">
                              <!-- <img :src="item.user.avatar_url" alt=""> -->
                              <p class="mr-10 ml-10">{{ item.user.nick_name }}</p>
                              <p>{{ item.user.mobile }}</p>
                            </div>
                            <div class="mt-10 oneline-hide" style="width: 250px;">
                              <a-popover>
                                <template slot="content">
                                  地址：{{ item.user?.address }}
                                </template>
                                地址：{{ item.user?.address }}
                              </a-popover>
                            </div>
                          </div>
                        </td>
                        <td :rowspan="item.goods.length">
                          <!-- <a-tag v-if="item.pay_method">{{ PaymentMethodEnum[item.pay_method].name }}</a-tag> -->
                          <span >{{ item.delivery_username || '--' }}</span>
                          <!-- <span v-else>--</span> -->
                        </td>
                        <td :rowspan="item.goods.length">
                          <!-- <a-tag v-if="item.pay_method">{{ PaymentMethodEnum[item.pay_method].name }}</a-tag> -->
                          <span v-if="item.merchant_remark">{{ item.merchant_remark }}</span>

                          <span v-else-if="item.pay_method">{{ item.pay_method }}</span>

                          <span v-else>--</span>
                        </td>
                        <!-- <td :rowspan="item.goods.length">
                          <a-tag>{{ DeliveryTypeEnum[item.delivery_type].name }}</a-tag>
                        </td> -->
                        <td :rowspan="item.goods.length">
                          <p class="mtb-2">
                            <span class="f-13">付款状态：</span>
                            <a-tag :color="item.pay_status == PayStatusEnum.SUCCESS.value ? 'green' : ''">{{
                              PayStatusEnum[item.pay_status].name
                            }}</a-tag>
                          </p>
                          <!-- <p class="mtb-2">
                            <span class="f-13">配送状态：</span>
                            <a-tag :color="item.delivery_status == DeliveryStatusEnum.DELIVERED.value ? 'green' : ''">{{
                              DeliveryStatusEnum[item.delivery_status].name
                            }}</a-tag>
                          </p> -->
                          <p class="mtb-2">
                            <span class="f-13">配送状态：</span>
                            <a-tag :color="item.receipt_status == ReceiptStatusEnum.RECEIVED.value ? 'green' : ''">{{
                              ReceiptStatusEnum[item.receipt_status].name
                            }}</a-tag>
                          </p>
                          <p v-if="[OrderStatusEnum.CANCELLED.value, OrderStatusEnum.APPLY_CANCEL.value].includes(
                            item.order_status
                          )
                          " class="mtb-2">
                            <span class="f-13">订单状态：</span>
                            <a-tag :color="renderOrderStatusColor(item.order_status)">{{
                              OrderStatusEnum[item.order_status].name
                            }}</a-tag>
                          </p>
                        </td>
                        <td :rowspan="item.goods.length">
                          <div class="actions">
                            <router-link v-if="$auth('/order/detail')"
                              :to="{ path: '/order/detail', query: { orderId: item.order_id } }"
                              target="_blank">详情</router-link>
                            <!-- <a v-action:deliver v-if="item.delivery_status === 10 && item.order_status < 20"
                              @click="handleDelivery(item)">发货</a>
                            <a v-action:cancel v-if="item.order_status == OrderStatusEnum.APPLY_CANCEL.value"
                              @click="handleCancel(item)">审核取消</a> -->
                            <!-- <a v-action:delete @click="handleDelete(item)">删除</a> -->
                            <a v-if="item.order_status < 20 && item.receipt_status !== 20" @click="cancelorder(item)">取消订单</a>
                            <a v-if="item.receipt_status === 20&& item.order_status < 30" @click="finishorder(item)">完成订单</a>
                            <a v-if="item.receipt_status === 20 && item.order_status < 30" @click="print(item)">打印</a>
                            <a v-if="item.run_id > 0 && item.receipt_status !== 20&& item.order_status == 10 " @click="cancelbind(item)">取消绑定</a>
                            <a v-if="item.run_id == 0 && item.receipt_status !== 20" @click="choosebind(item)">绑定配送员</a>
                            <a v-if="item.receipt_status !== 20 && item.order_status == 10" @click="choosebindstore(item)">转给门店</a>

                          </div>
                        </td>
                      </template>
                    </tr>
                  </template>
                </tbody>
              </table>
            </div>
            <!-- 空状态 -->
            <a-empty v-if="!orderList.data.length" :image="simpleImage" />
          </div>
        </div>
      </div>
      <!-- 分页器 -->
      <div v-if="orderList.data.length" class="pagination">
        <a-pagination :current="page" :pageSize="orderList.per_page" :total="orderList.total" @change="onChangePage" />
      </div>
      <DeliveryForm ref="DeliveryForm" @handleSubmit="handleRefresh" />
      <CancelForm ref="CancelForm" @handleSubmit="handleRefresh" />
    </a-spin>
    <!-- 录入订单 -->
    <a-modal :dialogStyle="orderdialogStyle" v-model="show" title="代下单" @ok="handleOk" width="700px">
      <a-spin :spinning="orderisLoading">
        <template>
          <div class="orderbox">
            <div class="orderitem">
              <p>门店：</p>
              <a-select style="width: 100%" placeholder="请选择门店" @change="handleChangeshop">
                <a-select-option v-for="i in shopListTreeData" :key="i.store_id">
                  {{ i.name }}
                </a-select-option>
              </a-select>
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem" style="width:150px">
              <p>商品：</p>
              <!-- <a-select style="width: 100%" placeholder="请选择商品" @change="handleChangegoods">
                <a-select-option v-for="i in goodslist" :key="i.goods_id" :disabled="i.stock_total>0?false:true" >
                  <span class="hidden" v-if="i.stock_total>0">{{ i.goods_name }}</span>
                  <span class="hidden" v-else >{{ i.goods_name }}--暂无库存</span>

                </a-select-option>
              </a-select> -->
              <a-button type="primary" @click="opengoodspop">选择商品</a-button>
            </div>
          </div>
          <div>
            <div class="goodsitembox" v-for="(i, index) in carlist" :key="index">
              <div class="goodsitembox_left">
                <img class="mr-10" :src="i.image" alt="">
                <div class="goodsitembox_left_text">
                  <p class="oneline-hide" style="width:80px">
                    <a-popover>
                      <template slot="content">
                        {{ i.name }}
                      </template>
                      {{ i.name }}
                    </a-popover>
                  </p>
                  <p style="color: lightcoral;">￥{{ i.price }}</p>
                </div>
              </div>
              <div class="goodsitembox_right">
                <p class="pointer" @click="deletegoods(index)">
                  <a-icon class="pointer" type="close-circle" />
                </p>
                <div class="bjq">
                  <p>数量：</p>
                  <p class="min pointer" @click="minnum(index)" :class="i.num == 1 ? 'active' : ''">一</p>
                  <a-input style="text-align: center; height:23px" placeholder="" v-model="i.num" />
                  <p class="plus pointer" @click="addnum(index)">➕</p>
                </div>
              </div>
            </div>
            <div class="heji">
              合计：
              <span style=" color: lightcoral; font-weight:bold; font-size:22px">￥{{ allprice }}</span>
            </div>
          </div>

          <div class="orderbox">
            <div class="orderitem">
              <p>客户：</p>
              <a-select v-model="customer" showSearch mode="combobox" style="width: 100%" placeholder="请选择客户"
                @change="handleChangecustomer">
                <a-select-option v-for="i in customerlist" :key="i.long_info">
                  {{ i.long_info }}
                </a-select-option>
              </a-select>
            </div>
            <div class="orderitem">
              <p>手机：</p>
              <a-input placeholder="请输入手机号" v-model="phone" />
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem" style="width: 400px;">
              <p>配送地址：</p>
              <a-input placeholder="请输入你要查找的关键词" v-model="userInput" id="tishikuang">
              </a-input>
            </div>
            <div class="">
              <p>坐标：{{ lng }}-{{ lat }}</p>
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>详细地址：</p>
              <a-input placeholder="请输入详细地址" v-model="detailaddress">
              </a-input>
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>配送时间：</p>

              <a-date-picker style="width: 100%" show-time placeholder="选择时间 " v-model="pre_times"
                format="YYYY-MM-DD HH:mm" @change="onOk" />
            </div>
          </div>
          <div class="orderbox">
            <div class="orderitem">
              <p>买家备注：</p>
              <a-textarea placeholder="请输入买家备注" v-model="buyer_remark" />
            </div>
          </div>
          <div id="container"></div>
        </template>
        <div class="orderbox">
          <div class="orderitem" style="width:100px">
            <p>费用：</p>
            <span class="" style="color: lightcoral; font-weight:bold; font-size:22px ">￥{{ allprice }}</span>
          </div>

        </div>
      </a-spin>
    </a-modal>

    <a-modal :dialogStyle="dialogStyle" width="720px" :mask="false" v-model="goodsvisible">
      <div class="modalbox ant-table">
        <a-input style="margin: 20px 0 ; width:70% " @input="goodschange" addon-before="商品名称 " v-model="goodsinput" />
        <!-- <table>
          <thead class="ant-table-thead ">
            <tr>
              <th
                style="padding: 20px 30px; background:rgb(222, 226, 226) "
                v-for="(item, index) in goodscolumns"
                :key="index">
                <span class="ant-table-header-column">
                  <div>
                    <span class="ant-table-column-title">{{ item }}</span>
                  </div>
                </span>
              </th>
            </tr>
          </thead>
          <tbody class="ant-table-tbody newtbody">
            <tr v-for="(i, index) in goodslist" :key="index">
              <td>
                <div class="goodsinfo_one">
                  <img :src="i.goods_image" alt="">
                  <span>{{ i.goods_name }}</span>
                </div>
              </td>
              <td>￥{{ i.goods_price_max }}</td>
              <td style="text-align: center;">{{ i.stock_total }}</td>
              <td style="text-align: center;">
                <a @click="choose(i)"><span>选择</span></a>
                <a @click="cancel(i)" style="color: lightcoral; padding-left:10px"><span>取消</span></a>
              </td>
            </tr>
          </tbody>
        </table> -->
        <div class="typebox">
          <div v-for="(i, index) in bigtype" @click="changebigtype(i.category_id)" class="pointer"
            :class="bigtypecurrent == i.category_id ? 'active' : 'typebox_item'" :key="index">
            {{ i.name }}
          </div>
        </div>
        <div class="typebox " style="margin-top: 5px;">
          <div v-if="showsmall" v-for="(i, index) in smalltype" class="pointer" @click="changesmalltype(i.category_id)"
            :class="smalltypecurrent == i.category_id ? 'active' : 'typebox_item'" :key="index">
            {{ i.name }}
          </div>
        </div>
        <div style="background-color: #D8D8D8; padding:20px 10px;margin:5px 10px">
          <div class="newgoodsbox">
            <div class="newgoodsbox_item pointer" @click="choose(i)" v-for="(i, index) in goodslist" :key="index">
              <img class="newgoodsbox_item_img" :src="i.goods_image" alt="">
              <div class="goodsname">{{ i.goods_name }}</div>
              <div class="pricebox">
                <span style="color: red">￥{{ i.goods_price_max }}</span>
                <span>
                  <img src="../../../src/assets/kc.png" class="kucun" alt="">
                  <span>{{ i.stock_total }}</span>
                </span>
              </div>
              <img class="choose_img" v-if="carlist.includes(i) == true" src="../../../src/assets/choose.png" alt="">
            </div>
          </div>
          <div class="pageclass">
            <a-pagination v-model="current" @change="changepage" :total="goodstotal" show-less-items />
          </div>
        </div>
      </div>
    </a-modal>

    <!-- <div class="warning_voice">
      <audio controls>
        <source src="../../../public/static/zxc.mp3" type="audio/ogg" />
        <source src="../../../public/static/zxc.mp3" type="audio/mpeg" />
        您的浏览器不支持 audio 元素。
      </audio>
    </div> -->
    <a-modal title="请填写支付备注" :visible="payvisible" @ok="payhandleOk" @cancel="payhandleCancel">

      <div style="margin: 20px 0;">
        <a-input placeholder="请填写备注：" v-model="add_remark" />
      </div>
    </a-modal>
    <audio ref="audio" class="aud">
      <source src="../../../public/static/zxc.mp3" />
    </audio>

    <a-modal :width="720" :visible="visible" @ok="handleSubmit" @cancel="visible = false">
      <div class="personbox">
        <div class="personitem pointer" @click="personcurrent = i.store_user_id"
          :class="personcurrent == i.store_user_id ? 'active' : ''" v-for="(i, index) in renderdeliverylist"
          :key="index">
          <div class="personitem_top">
            <p class="name">{{ i.real_name }}</p>
            <p>配送中：{{ i.delivery_order_count }}单</p>
          </div>
          <div class="shop">
            {{ i.store_name }}
          </div>
        </div>
      </div>
    </a-modal>

    <a-modal :width="720" :visible="shopvisible" @ok="shophandleSubmit" @cancel="shopvisible = false">
      <div class="personbox">
        <a-select style="width: 200px;" v-model="store_id">
          <a-select-option v-for="(item, index) in renderstoreList" :disabled="item.disabled" :key="index"
            :value="item.store_id">{{
              item.store_name
            }}</a-select-option>
        </a-select>
      </div>
    </a-modal>
  </a-card>
</template>

<script>
// 引入高德地图
import AMapLoader from '@amap/amap-jsapi-loader'
import { Empty } from 'ant-design-vue'
import { inArray, assignment } from '@/utils/util'
import * as ApiHome from '@/api/home'
import * as Api from '@/api/order'
import * as EventApi from '@/api/order/event'
import PlatformIcon from '@/components/PlatformIcon'
import { GoodsItem, UserItem } from '@/components/Table'
import * as shopApi from '@/api/store/user'
import { SelectRegion } from '@/components'

import {
  DeliveryStatusEnum,
  DeliveryTypeEnum,
  OrderSourceEnum,
  OrderStatusEnum,
  PayStatusEnum,
  ReceiptStatusEnum
} from '@/common/enum/order'
import { DeliveryForm, CancelForm } from './modules'
window._AMapSecurityConfig = {
  securityJsCode: '7f9f1cdc2ff12403fd937336164e10cf'// 在这里填写你的安全密钥
}
const goodscolumns = [
  '商品信息',
  '价格',
  '库存',
  '操作'
]
// 表格字段
const columns = [
  {
    title: '商品信息',
    align: 'center',
    dataIndex: 'goods',
    scopedSlots: { customRender: 'goods' }
  },
  {
    title: '单价/数量',
    align: 'center',
    scopedSlots: { customRender: 'unit_price' }
  },
  {
    title: '实付款',
    align: 'center',
    dataIndex: 'pay_price',
    scopedSlots: { customRender: 'pay_price' }
  },
  {
    title: '客户信息',
    dataIndex: 'user',
    scopedSlots: { customRender: 'user' }
  },
  {
    title: '配送员',
    dataIndex: 'delivery_username',
    scopedSlots: { customRender: 'delivery_username' }
  },
  {
    title: '支付方式',
    dataIndex: 'pay_method',
    scopedSlots: { customRender: 'pay_method' }
  },
  // {
  //   title: '配送方式',
  //   dataIndex: 'delivery_type',
  //   scopedSlots: { customRender: 'delivery_type' }
  // },
  {
    title: '交易状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    scopedSlots: { customRender: 'action' }
  }
]

// 搜索关键词类型枚举
const SearchTypeEnum = [
  { name: '银豹订单号', value: 10 },
  { name: '商品名称', value: 15 },
  { name: '配送员名字', value: 20 },
  // { name: '会员ID', value: 30 },
  { name: '收货人姓名', value: 40 },
  { name: '收货人电话', value: 50 }
]

const data = {
  pending: {
    deliverOrderTotal: 0,
    refundTotal: 0,
    paidOrderTotal: 0,
    soldoutGoodsTotal: 0
  }
}

export default {
  name: 'Index',
  components: {
    PlatformIcon,
    GoodsItem,
    UserItem,
    DeliveryForm,
    CancelForm,
    SelectRegion,
  },
  data() {
    return {
      personcurrent: 0,
      shopvisible: false,
      visible: false,
      payvisible: false,
      audio: new Audio(require('../../../public/static/zxc.mp3')),
      // 关于地图的配置
      map: null,
      pre_times: '',
      autoOptions: {
        input: 'tishikuang' // 绑定的搜索关键字的input标签ID，用这个注册
      },
      // 地址逆解析
      geoCoder: null,
      bigtype: [],
      smalltype: [],

      auto: null,
      bigtypecurrent: 0,
      smalltypecurrent: 0,

      userInput: '', // 绑定的搜索关键字的的内容
      placeSearch: null,
      searchHere: null, // 根据搜索组件搜索到以后的地点信息
      lng: '',
      lat: '',
      address: '',
      // 关于地图的配置
      dialogStyle: {
        top: '100px',
        left: '450px'
      },
      orderdialogStyle: {
        top: '100px',
        right: '300px'
      },
      goodsvisible: false,
      detailaddress: '',
      goods_num: 0,
      show: false,
      goodslist: [],
      shopListTreeData: [],
      carlist: [],
      current: 1,
      // 订单类型
      dataType: this.getDataType(),
      // 当前表单元素
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 表格字段
      orderisLoading: false,
      columns,
      // 当前页码
      goodscolumns,
      page: 1,
      timer: '',
      goodstotal: '',
      // 列表数据
      orderList: { data: [], total: 0, per_page: 10 },
      store_id: '',
      customer: '',
      customerlist: [],
      phonelist: [],
      phone: '',
      // 支付方式列表
      PaymentMethodEnum: [],
      // 备注
      merchant_remark: '',
      buyer_remark: '',
      data,
      goodspage: 1,
      goodsName: '',
      goodsinput: '',
      orderId: '',
      add_remark: '',
      showsmall: false,
      category_id: '',
      renderdeliverylist: [],
      renderstoreList: []
    }
  },
  beforeCreate() {
    // 批量给当前实例赋值
    assignment(this, {
      inArray,
      DeliveryStatusEnum,
      DeliveryTypeEnum,
      OrderSourceEnum,
      OrderStatusEnum,
      PayStatusEnum,
      ReceiptStatusEnum,
      SearchTypeEnum,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE
    })
  },
  watch: {
    // 监听路由变化
    $route() {
      this.init()
    },
    orderList(newval, oldval) {
      console.log('我是列表数据', newval.total, oldval.total)
      if (oldval.total !== 0) {
        if (newval.total !== oldval.total) {
          console.log('bofang')
          this.playAudio()
        }
      }
    }
  },
  computed: {
    allprice() {
      if (this.carlist.length === 0) {
        return 0
      } else {
        return this.carlist.reduce((price, ele) => {
          price += ele.price * ele.num
          return price
        }, 0)
      }
    }
  },
  created() {
    // 初始化页面
    this.play()
    this.init()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  mounted() {
    this.getshoplist()
    this.getcustomer()
    this.getpayway()
  },
  methods: {
    //配送员列表
    getdeliveryList() {
      EventApi.deliveryList().then(res => {
        this.renderdeliverylist = res.data.list
      })
    },
    //选择门店列表
    getstoreList(store_id) {
      EventApi.storeList().then(res => {
        this.renderstoreList = res.data.list
        this.renderstoreList.map(item => {
          if (item.store_id == store_id) {
            item.disabled = true
          }
        })

      })
    },
    changebigtype(id) {
      this.showsmall = true
      this.bigtypecurrent = id
      this.smalltypecurrent = ''
      this.getsmalltype(id)
    },
    changesmalltype(id) {
      this.goodspage = 1
      this.showsmall = false
      this.smalltypecurrent = id
      this.category_id = id
      this.getgoodslist()
    },

    // 获取一级分类
    getbigtype(id) {
      Api.bigtype({ store_id: id }).then(res => {
        this.bigtype = res.data
        this.bigtypecurrent = res.data[0].category_id
      })
    },
    // 获取2级分类
    getsmalltype(id) {
      Api.smalltype({ uid: id, store_id: this.store_id }).then(res => {
        this.smalltype = res.data
      })
    },
    playAudio() {
      let music1 = new Audio()
      music1 = require('../../../public/static/zxc.mp3')
      this.$refs.audio.src = music1
      this.$refs.audio.play()
    },

    stopAudio() {
      if (
        this.audio.currentTime > 0 &&
        !this.audio.paused &&
        !this.audio.ended &&
        this.audio.readyState > 2
      ) { // 停止播放音频
        this.audio.pause()
      } else { // 重置音频时间轴
        this.audio.currentTime = 0
        this.audio.pause()
      }
    },
    // 选择或者取消选择商品
    choose(i) {
      if (i.stock_total === 0) {
        this.$message.warning('暂无库存~')
        return false
      }
      if (this.carlist.length > 0) {
        this.carlist.forEach(item => {
          if (i.goods_id === item.goods_id) {
            // this.carlist.splice(this.carlist.indexOf(i.goods_id), 1)
            this.$message.success('您已经添加过该商品~')
          }
        })
      } else {
        const obj = {
          image: i.goods_image,
          price: i.goods_price_max,
          name: i.goods_name,
          num: 1,
          goods_id: i.goods_id
        }
        this.carlist.push(obj)
      }

      if (this.carlist.length > 0) {
        console.log(this.carlist.some(item => {
          return item.goods_id === i.goods_id
        }))
        var a = this.carlist.some(item => {
          return item.goods_id === i.goods_id
        })
        if (!a) {
          const obj = {
            image: i.goods_image,
            price: i.goods_price_max,
            name: i.goods_name,
            num: 1,
            goods_id: i.goods_id
          }
          this.carlist.push(obj)
        }
      }
    },
    cancel(i) {
      let zxc
      this.carlist.map(item => {
        if (i.goods_id === item.goods_id) {
          zxc = true
        } else {
          zxc = false
        }
      })
      if (zxc) {
        //  this.carlist.splice(index, 1)
        this.carlist = this.carlist.filter(function (item) {
          return item.goods_id !== i.goods_id
        })
      } else {
        this.$message.success('请先添加该商品~')
      }
    },
    // 打开商品列表pop
    opengoodspop() {
      if (this.store_id) {
        this.goodsvisible = true
      } else {
        this.$message.warning('请先选择门店~')
      }
    },
    // 完成订单
    finishorder(item) {
      this.orderId = item.order_id
      this.payvisible = true

      // const modal = that.$confirm({
      //   title: '您确定要完成该订单吗?',
      //   content: '',
      //   onOk () {
      //     return Api.finishorder({ order_id: item.order_id, add_remark: this.add_remark })
      //       .then(async result => {
      //         that.$message.success(result.message, 1.5)
      //         await that.handleRefresh(true)
      //       })
      //       .finally(result => modal.destroy())
      //   }
      // })
    },
    payhandleOk() {
      var that = this
      Api.finishorder({ order_id: this.orderId, add_remark: this.add_remark })
        .then(async result => {
          that.$message.success(result.message, 1.5)
          await that.handleRefresh(true)
        })
        .finally(res => {
          that.payvisible = false
        })
    },
    payhandleCancel() {
      this.payvisible = false
    },
    // 取消订单
    cancelorder(item) {
      const that = this
      const modal = that.$confirm({
        title: '您确定要取消该记订单吗?',
        content: '',
        onOk() {
          return Api.cancelOrder({ order_id: item.order_id })
            .then(async result => {
              that.$message.success(result.message, 1.5)
              await that.handleRefresh(true)
            })
            .finally(result => modal.destroy())
        }
      })
    },
    // 获取支付方式筛选列表
    getpayway() {
      Api.getpayway({}).then(res => {
        this.PaymentMethodEnum = res.data
        
      })
    },
    // 获取用户列表
    getcustomer() {
      shopApi.getuser({})
        .then(res => {
          this.customerlist = res.data

          this.phonelist = res.data.phone
        })
        .finally(result => {

        })
    },
    goodschange(e) {
      this.goodsinput = e.target.value
      shopApi.getgoods({ store_id: this.store_id, listRows: 6, category_id: this.category_id, page: this.goodspage, goodsName: this.goodsinput })
        .then(result => {
          this.goodslist = result.data.list.data
          this.goodstotal = result.data.list.total
        })
        .finally(result => {

        })
    },

    handleChangecustomer(e) {
      this.customerlist.map(item => {
        if (item.long_info === e) {
          this.customer = item.name
          this.phone = item.phone
          this.user_id = item.user_id
          this.detailaddress = item.address_detail
          this.userInput = item.address
          this.lng = item.longitude
          this.lat = item.latitude
        }
      })
    },
    // 下单
    makeorder() {
      if (!this.lng || !this.lat) {
        this.$message.warning('请重新选择地址~')
        return false
      }
      if (!this.store_id) {
        this.$message.warning('请选择门店~')
        return false
      }
      if (this.carlist.length === 0) {
        this.$message.warning('请选择商品~')
        return false
      }
      if (!this.phone) {
        this.$message.warning('请输入手机号~')
        return false
      }

      if (!this.detailaddress) {
        this.$message.warning('请补充详细地址~')
        return false
      }
      this.orderisLoading = true
      Api.makeorder({
        store_id: this.store_id,
        carlist: this.carlist,
        price: this.allprice,
        customer: this.customer,
        phone: this.phone,
        latitude: this.lat,
        pre_times: this.pre_times,
        longitude: this.lng,
        // merchant_remark: this.merchant_remark,
        buyer_remark: this.buyer_remark,
        address: this.userInput,
        address_detail: this.detailaddress
      }).then(async res => {
        this.orderisLoading = false

        this.$message.success('创建成功~')
        this.show = false
        await this.handleRefresh(true)
      }).finally(res => {
        this.orderisLoading = false
      })
    },
    // 获取门店列表
    getshoplist() {
      shopApi.getshop({})
        .then(result => {
          result.data.map(item => {
            item.name = item.store_name
          })
          this.shopListTreeData = result.data
        })
        .finally(result => {

        })
    },
    // 获取当前门店商品列表
    getgoodslist() {
      shopApi.getgoods({ store_id: this.store_id, listRows: 6, category_id: this.category_id, page: this.goodspage, goodsName: this.goodsinput })
        .then(result => {
          this.goodslist = result.data.list.data
          this.goodstotal = result.data.list.total
        })
        .finally(result => {

        })
    },
    changepage(e) {
      this.goodspage = e
      shopApi.getgoods({ store_id: this.store_id, listRows: 6, category_id: this.category_id, page: this.goodspage, goodsName: this.goodsinput })
        .then(result => {
          this.goodslist = result.data.list.data
          this.goodstotal = result.data.list.total
        })
        .finally(result => {

        })
    },
    // 选择商品
    handleChangegoods(e) {
      this.goodslist.map(item => {
        if (item.goods_id === e) {
          item.goods_num = 1
          const obj = {
            image: item.goods_image,
            price: item.goods_price_max,
            name: item.goods_name,
            num: 1,
            goods_id: item.goods_id
          }
          this.carlist.push(obj)
        }
      })
    },
    // 选择门店
    handleChangeshop(e) {
      this.carlist = []
      this.store_id = e

      this.getgoodslist()
      this.getbigtype(e)
    },
    deletegoods(index) {
      this.carlist.splice(index, 1)
    },
    minnum(index) {
      if (this.carlist[index].num === 1) {
        this.carlist[index].num = 1
      } else {
        this.carlist[index].num -= 1
      }
    },
    addnum(index) {
      this.carlist[index].num += 1
    },
    addorder() {
      this.show = true // 打开弹窗指令
      this.$nextTick(() => {
        // 初始化地图
        this.initMap()
      })
    },
    async handleOk() {
      await this.makeorder()
    },
    play() {
      this.timer = setInterval(this.getList, 60000)
    },
    // 初始化页面
    init() {
      this.dataType = this.getDataType()
      this.searchForm.resetFields()
      this.queryParam = {}
      this.handleRefresh(true)

      this.isLoading = true
      ApiHome.data().then((result) => {
        this.data = result.data.data
      })
    },

    // 获取当前标签
    getDataType() {
      return this.$route.path.split('/')[3].replace('-', '_')
    },

    // 获取列表数据
    getList() {
      const { dataType, queryParam, page } = this
      this.isLoading = true
      return Api.list({ dataType, ...queryParam, page })
        .then((response) => {
          this.orderList = response.data.list
        })
        .finally(() => (this.isLoading = false))
    },

    // 渲染订单状态标签颜色
    renderOrderStatusColor(orderStatus) {
      const { OrderStatusEnum } = this
      const ColorEnum = {
        [OrderStatusEnum.NORMAL.value]: '',
        [OrderStatusEnum.CANCELLED.value]: 'red',
        [OrderStatusEnum.APPLY_CANCEL.value]: 'red',
        [OrderStatusEnum.COMPLETED.value]: 'green'
      }
      return ColorEnum[orderStatus]
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh(bool = false) {
      bool && (this.page = 1)
      this.getList()
    },

    // 确认搜索
    handleSearch(e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },

    // 重置搜索表单
    handleReset() {
      this.searchForm.resetFields()
    },

    // 翻页事件
    onChangePage(current) {
      this.page = current
      this.handleRefresh()
    },
    //确定转让门店
    shophandleSubmit() {
      if (!this.store_id) {
        return this.$message.error('请选择门店')
      }
      EventApi.bindStore({ order_id: this.orderId, store_id: this.store_id })
        .then((result) => {
          this.$message.success(result.message, 1.5)
          this.handleRefresh()
          this.shopvisible = false
        })
        .catch((error) => {

        })
    },
    //确定选择一个配送员
    handleSubmit() {
      if (!this.personcurrent) {
        return this.$message.error('请选择配送员')
      }
      EventApi.bindRun({ order_id: this.orderId, run_id: this.personcurrent })
        .then((result) => {
          this.$message.success(result.message, 1.5)
          this.handleRefresh()
          this.visible = false
        })
        .finally((result) => {

        })
    },
    choosebind(item) {
      this.getdeliveryList()

      this.orderId = item.order_id
      this.visible = true
    },
    choosebindstore(item) {
      this.getstoreList(item.store_id)
      this.orderId = item.order_id
      this.shopvisible = true
    },
    //取消绑定
    cancelbind(item) {
      const app = this
      const modal = app.$confirm({
        title: '提示',
        content: '您确定要取消绑定吗?',
        onOk() {
          return EventApi.cancelBind({ order_id: item.order_id })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    //打印小票
    print(item) {
      const app = this
      const modal = app.$confirm({
        title: '提示',
        content: '您确定要打印小票吗?',
        onOk() {
          return EventApi.printer({ order_id: item.order_id })
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },
    // 删除记录
    handleDelete(item) {
      const app = this
      const modal = app.$confirm({
        title: '您确定要删除该订单记录吗?',
        content: '删除后不可恢复，请谨慎操作',
        onOk() {
          return EventApi.deleted(item.order_id)
            .then((result) => {
              app.$message.success(result.message, 1.5)
              app.handleRefresh()
            })
            .finally((result) => modal.destroy())
        }
      })
    },

    // 订单发货
    handleDelivery(record) {
      this.$refs.DeliveryForm.show(record)
    },
    onOk(date, dateString) {
      this.pre_times = dateString
    },
    // 审核取消订单
    handleCancel(record) {
      this.$refs.CancelForm.show(record)
    },
    initMap() {
      const that = this
      AMapLoader.load({
        key: '7d1135f723e6c3892a1a271d219a33f2', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType',
          'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.PlaceSearch', 'AMap.Geocoder'
        ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        this.map = new AMap.Map('container', { // 设置地图容器id
          viewMode: '3D', // 是否为3D地图模式
          zoom: 17, // 初始化地图级别
          center: [114.819185, 34.814411] // 初始化地图中心点位置
        })
        // 地址逆解析插件
        this.geoCoder = new AMap.Geocoder({
          city: '010', // 城市设为北京，默认：“全国”
          radius: 1000 // 范围，默认：500
        })

        // 引入高德地图的空间绑定使用
        this.map.addControl(new AMap.Scale())
        this.map.addControl(new AMap.ToolBar())
        this.map.addControl(new AMap.HawkEye())
        this.map.addControl(new AMap.MapType())
        this.map.addControl(new AMap.Geolocation())
        this.auto = new AMap.AutoComplete(this.autoOptions)
        //
        this.placeSearch = new AMap.PlaceSearch({
          map: this.map
        }) // 构造地点查询类
        this.auto.on('select', this.select)// 绑定查询事件
        this.map.on('click', function (e) {
          that.lng = e.lnglat.getLng()
          that.lat = e.lnglat.getLat()
          that.toGeoCoder()

          that.biu()
        })
      }).catch(e => {
        console.log(e)
      })
    },
    // 逆解析地址
    toGeoCoder() {
      const lnglat = [this.lng, this.lat]
      this.geoCoder.getAddress(lnglat, (status, result) => {
        if (status === 'complete' && result.regeocode) {
          console.log(result.regeocode.formattedAddress)
          this.userInput = result.regeocode.formattedAddress
        }
      })
    },

    biu() {
      if (this.searchHere) {
        console.log(this.searchHere, 'hhh')
        // this.$emit('mapHere',this.searchHere);
      }
    },
    select(e) {
      this.placeSearch.setCity(e.poi.adcode) // 依据城市ID搜索
      this.placeSearch.search(e.poi.name) // 关键字查询查询
      this.map.setZoom(10, true)
      this.searchHere = e.poi
      // this.$message({
      //   message: '选择地点:' + this.searchHere.name,
      //   type: 'success'
      // })
      this.lng = this.searchHere.location.lng
      this.lat = this.searchHere.location.lat
      this.userInput = this.searchHere.name
    }

  }
}
</script>
<style lang="less" scoped>
.card-number {
  color: #f20;
  padding: 20px;
  box-sizing: border-box;
}

// 分页器
.pagination {
  margin-top: 16px;

  .ant-pagination {
    float: right;
  }
}

.ant-table {
  table {
    border: none;
    border-collapse: collapse;
  }

  .ant-table-thead>tr {
    border: 1px solid #e8e8e8;
  }

  tr.order-empty {
    height: 15px;
    border: 1px solid #fff;

    td {
      padding: 0;
      border-right: none;
      border-left: none;
      background: none !important;
    }
  }
}

.ant-table-thead>tr>th {
  border-right: none;
  border-bottom: none;
  padding: 12px 12px;
  font-weight: bold;
}

.ant-table-tbody>tr>td {
  border-right: 1px solid #e8e8e8;
  border-left: 1px solid #e8e8e8;
  padding: 12px 12px;
  // text-align: center;
}

.userinfo_top {
  display: flex;
  align-items: center;

  >img {
    width: 20px;
    height: 20px;
    border-radius: 50%;
  }
}

/deep/.ant-modal {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  color: rgba(0, 0, 0, 0.65);
  font-size: 13px;
  font-variant: tabular-nums;
  line-height: 1.5;
  list-style: none;
  -webkit-font-feature-settings: 'tnum';
  font-feature-settings: 'tnum';
  position: relative;
  top: 50px;
  width: auto;
  margin: 0 auto;
  padding-bottom: 24px;
  pointer-events: none;
}

.orderbox {
  display: flex;
  align-items: center;

  .orderitem {
    width: 300px;
    margin: 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    >p {
      flex-shrink: 0;
      text-align: right;
      width: 70px;

    }
  }

}

#container {
  padding: 0px;
  margin: 10px 0px 0px 75px;
  width: 532px;
  height: 300px;
}

.bjq {
  display: flex;
  align-items: center;
  width: 130px;
  margin-left: 30px;

  >p {
    flex-shrink: 0;
  }

  .pointer {
    cursor: pointer;
  }

  .min {
    border: 1px solid #d9d9d9;
    padding: 0px 5px;
  }

  .active {
    background-color: #dddcdc;
  }

  .plus {
    border: 1px solid #d9d9d9;
    padding: 0px 5px;
  }
}

.heji {
  align-items: center;
  display: flex;
  justify-content: flex-end;
  width: 300px;

}

.goodsitembox {
  margin: 20px;
  width: 300px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .goodsitembox_left {
    display: flex;
    width: 100px;

    img {
      width: 60px;
      height: 60px;

    }

    .goodsitembox_left_text {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      height: 60px;
    }
  }

  .goodsitembox_right {
    display: flex;
    flex-direction: column;
    height: 60px;
    justify-content: space-between;
    align-items: end;
  }
}

.orderinfo {
  display: flex;
  align-items: center;
}

.shopinfo {
  display: flex;
  align-items: center;
}

.shopimg {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.newtbody {
  tr {
    border: 1px solid #cbc8c8;

    >td {
      border: 1px solid #cbc8c8;
    }
  }

}

.goodsinfo_one {
  img {
    width: 60px;
    height: 60px;
  }
}

.modalbox {

  width: 650px;

  .pageclass {

    width: 650px;
    padding: 30px 0;
  }
}

.typebox {
  background-color: #5FA4E7;
  border-radius: 20px;
  width: 100%;
  display: flex;
  align-items: center;
  color: #fff;
  overflow-x: auto;

  .active {
    background-color: #387FD7;
    padding: 15px 30px;
    flex-shrink: 0;

  }

  .typebox_item {
    padding: 15px 30px;
    flex-shrink: 0;

  }
}

.newgoodsbox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .newgoodsbox_item {
    position: relative;
    width: 180px;
    border-radius: 10px;
    margin: 20px 10px;
    background-color: #fff;
    padding: 15px;
    display: flex;
    align-items: center;
    flex-direction: column;
    justify-content: center;

    .goodsname {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      width: 100%;
    }

    .newgoodsbox_item_img {
      width: 50px;
      height: 50px;
      margin-bottom: 10px;
    }

    .pricebox {
      margin: 10px 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .kucun {
      width: 20px;
      height: 20px
    }

    .choose_img {
      width: 20px;
      height: 20px;
      position: absolute;
      top: 10px;
      right: 20px;
    }
  }
}

.personbox {
  padding-top: 40px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .personitem {
    margin: 10px;
    width: 200px;
    padding: 10px;
    background-color: #F8FAFF;

    .personitem_top {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .name {
        color: #6F6F6F;
        font-size: 16px;
      }
    }

    .shop {
      color: #7C7E80;
      font-size: 12px;
    }
  }

  .active {
    border: 1px solid #7499FF;

    background: #D9E3FD;
  }
}
</style>
